package wang.raye.viewlib;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ListView;

/**
 * Created by Raye on 2015/12/2.
 */
public class ScrollListView  extends ListView {

    private int mItemCount;
    private int mItemOffsetY[];
    private boolean scrollIsComputed = false;
    private int mHeight;

    public ScrollListView(Context context) {
        super(context);
    }

    public ScrollListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public int getListHeight() {
        return mHeight;
    }

    public void computeScrollY() {
        mHeight = 0;
        if(getAdapter() == null){
            return;
        }
        mItemCount = getAdapter().getCount();
        if (mItemOffsetY == null || mItemCount != mItemOffsetY.length) {
            mItemOffsetY = new int[mItemCount];
        }
        int height = 0;
        for (int i = 0; i < mItemCount; ++i) {
            //为了防止动画失效采取的方法
            if(i < 2 || i == mItemCount - 1){
                //是前面2个或者最后一个
                View view = getAdapter().getView(1, null, this);
                view.measure(
                        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
                        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                mItemOffsetY[i] = mHeight;
                height = view.getMeasuredHeight();
                mHeight += height;
            }else{
                //中间的
                mItemOffsetY[i] = mHeight;
                mHeight += height;
            }

        }

        scrollIsComputed = true;
    }

    public boolean scrollYIsComputed() {
        return scrollIsComputed;
    }

    public int getComputedScrollY() {
        int pos, nScrollY, nItemY;
        View view = null;
        pos = getFirstVisiblePosition();
        view = getChildAt(0);
        nItemY = view.getTop();
        nScrollY = mItemOffsetY[pos] - nItemY;
        return nScrollY;
    }
}

